package main

import (
	"fmt"
	"os"
	"strings"
	"time"
)

// 保存环境
func handleSave(args []string) {
	if len(args) == 0 {
		fmt.Println("请指定环境名称")
		fmt.Println("用法: genv save <环境名>")
		os.Exit(1)
	}

	baseName := args[0]
	finalName := baseName

	// 检查名称冲突
	if envMap := getAllEnvNames(); envMap[baseName] {
		timestamp := time.Now().Format("20060102150405") // 格式示例: 20230701235959
		finalName = fmt.Sprintf("%s_%s", baseName, timestamp)
		fmt.Printf("环境 %s 已存在，自动重命名为: %s\n", baseName, finalName)
	}

	_, err := runGit("stash", "save", "-u", finalName)
	if err != nil {
		fmt.Printf("保存失败: %v\n", err)
		return
	}
	fmt.Printf("已保存环境: %s\n", finalName)
}

// 获取所有环境名称
func getAllEnvNames() map[string]bool {
	envMap := make(map[string]bool)
	output, err := runGit("stash", "list")
	if err != nil {
		return envMap
	}

	lines := strings.Split(output, "\n")
	for _, line := range lines {
		if parts := strings.SplitN(line, ": ", 3); len(parts) >= 3 {
			envName := parts[2]
			envMap[envName] = true
		}
	}
	return envMap
}
